package com.gewu.pm.ui.fragment.delivery;

import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.Permissions;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.delivery.InvoiceViewActivity;
import com.gewu.pm.ui.adapter.delivery.DeliveryProviderReconciliationAdapter;
import com.gewu.pm.ui.dialog.MenuDialog;
import com.hjq.base.BaseDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import timber.log.Timber;

/**
 * 配送商对账 Fragment
 */
public final class DeliveryProviderReconciliationFragment extends AppFragment<AppActivity>
        implements DeliveryProviderReconciliationAdapter.OnActionListener {

    private RecyclerView mRecyclerView;
    private DeliveryProviderReconciliationAdapter mAdapter;

    private int mReconciliationType;  // 对账类型（0=待确认，1=已确认）
    private List<String> mDataList = new ArrayList<>();

    private static final int REQUEST_CAMERA = 1;
    private static final int REQUEST_ALBUM = 2;

    public static DeliveryProviderReconciliationFragment newInstance(int reconciliationType) {
        DeliveryProviderReconciliationFragment fragment = new DeliveryProviderReconciliationFragment();
        Bundle args = new Bundle();
        args.putInt(IntentKey.TYPE, reconciliationType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.delivery_provider_reconciliation_fragment;
    }

    @Override
    protected void initView() {
        mRecyclerView = findViewById(R.id.rv_list);

        if (getArguments() != null) {
            mReconciliationType = getArguments().getInt(IntentKey.TYPE, 0);
        }

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new DeliveryProviderReconciliationAdapter(getContext(), mReconciliationType);
        mAdapter.setOnActionListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        // 创建测试数据
        createTestData();
        mAdapter.setData(mDataList);
    }

    /**
     * 创建测试数据
     */
    private void createTestData() {
        mDataList.clear();
        mDataList.add("2025/08/01—2025/08/31");
        mDataList.add("2025/07/01—2025/07/31");
        mDataList.add("2025/06/01—2025/06/30");
        mDataList.add("2025/05/01—2025/05/31");
    }

    @Override
    public void onUploadInvoice(int position) {
        // 显示底部菜单（拍摄、从相册中上传、取消）
        showUploadInvoiceMenu();
    }

    @Override
    public void onViewInvoice(int position) {
        // 跳转到查看发票页面
        InvoiceViewActivity.start(getContext());
    }

    /**
     * 显示上传发票菜单
     */
    private void showUploadInvoiceMenu() {
        List<String> menuList = Arrays.asList("拍摄", "从相册中上传");

        new MenuDialog.Builder(getContext())
                .setList(menuList)
                .setListener(new MenuDialog.OnListener<String>() {
                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        if (position == 0) {
                            // 拍摄
                            openCamera();
                        } else if (position == 1) {
                            // 从相册中上传
                            openAlbum();
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        // 取消
                    }
                })
                .show();
    }

    /**
     * 打开相机
     */
    @Permissions(android.Manifest.permission.CAMERA)
    private void openCamera() {
        try {
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getContext().getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_CAMERA);
            } else {
                toast("无法打开相机");
            }
        } catch (Exception e) {
            Timber.e(e, "打开相机失败");
            toast("打开相机失败");
        }
    }

    /**
     * 打开相册
     */
    @Permissions(android.Manifest.permission.READ_MEDIA_IMAGES)
    private void openAlbum() {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            if (intent.resolveActivity(getContext().getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_ALBUM);
            } else {
                toast("无法打开相册");
            }
        } catch (Exception e) {
            Timber.e(e, "打开相册失败");
            toast("打开相册失败");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode == AppActivity.RESULT_OK && data != null) {
            if (requestCode == REQUEST_CAMERA) {
                // 拍照返回
                toast("拍照成功");
            } else if (requestCode == REQUEST_ALBUM) {
                // 相册返回
                if (data.getData() != null) {
                    String photoPath = data.getData().toString();
                    toast("照片地址：" + photoPath);
                }
            }
        }
    }

    /**
     * 操作监听接口
     */
    public interface OnActionListener {
        /**
         * 上传发票
         */
        void onUploadInvoice(int position);

        /**
         * 查看发票
         */
        void onViewInvoice(int position);
    }
}

